package com.ohos.ringdroid.slice;

import com.ohos.ringdroid.LogUtil;
import com.ohos.ringdroid.MusicBean;
import com.ohos.ringdroid.ResourceTable;
import com.ohos.ringdroid.core.EditAbility;
import com.ohos.ringdroid.core.MusicPlayerAbility;
import com.ohos.ringdroid.core.slice.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.components.element.ElementScatter;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.ohos.ringdroid.LogUtil.LABEL_LOG;
import static com.ohos.ringdroid.LogUtil.TAG_LOG;
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;


public class MainAbilitySlice extends AbilitySlice {
    // Result codes
    private static final int REQUEST_CODE_EDIT = 1;
    private static final int REQUEST_CODE_CHOOSE_CONTACT = 2;

    public ListContainer listContainer = new ListContainer(getContext());
    public ResultSet resultSet;
    public DataAbilityHelper helper;
    public final String TYPE_MUSIC = "TYPE_MUSIC";
    public final String TYPE_ALARM = "TYPE_ALARM";
    public final String TYPE_RINGTONE = "TYPE_RINGTONE";
    public final String TYPE_NOTIFICATION = "TYPE_NOTIFICATION";
    public final String TYPE_UNSUPPORTED = "TYPE_UNSUPPORTED";

    public Text titleText;
    public TextField searchBar;
    public Image backButton, searchButton, recordButton, menuButton;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initView();

        listContainer = (ListContainer) findComponentById(ResourceTable.Id_list);
        List<MusicBean> musicBeans = new ArrayList<>();

        helper = DataAbilityHelper.creator(getContext());
        DataAbilityPredicates pre = new DataAbilityPredicates();
        try {
            pre.contains(AVStorage.AVBaseColumns.TITLE, "A");
            resultSet = helper.query(AVStorage.Audio.Media.INTERNAL_DATA_ABILITY_URI, null, null);
            if (resultSet == null) {
                return;
            }
            LogUtil.info(TAG_LOG, "get getAllColumnNames: " + Arrays.toString(resultSet.getAllColumnNames()));
            LogUtil.info(TAG_LOG, "get getColumnCount: " + resultSet.getColumnCount());
            LogUtil.info(TAG_LOG, "get order: " + pre.getOrder());

            while (resultSet.goToNextRow()) {
                MusicBean musicBean = new MusicBean();
                musicBean.setId(resultSet.getInt(resultSet.getColumnIndexForName(AVStorage.AVBaseColumns.ID)));
                musicBean.setData(resultSet.getString(resultSet.getColumnIndexForName(AVStorage.AVBaseColumns.DATA)));
                musicBean.setTitle_uri(resultSet.getString(resultSet.getColumnIndexForName("title_resource_uri")));
                musicBean.setAlbum(resultSet.getString(resultSet.getColumnIndexForName("album")));
                musicBean.setArtist(resultSet.getString(resultSet.getColumnIndexForName("artist")));
                musicBean.setDuration(resultSet.getString(resultSet.getColumnIndexForName(AVStorage.AVBaseColumns.DURATION)));
                musicBean.setTitle(resultSet.getString(resultSet.getColumnIndexForName(AVStorage.AVBaseColumns.TITLE)));
                musicBean.setIs_alarm(resultSet.getString(resultSet.getColumnIndexForName("is_alarm")));
                musicBean.setIs_music(resultSet.getString(resultSet.getColumnIndexForName("is_music")));
                musicBean.setIs_notification(resultSet.getString(resultSet.getColumnIndexForName("is_notification")));
                musicBean.setIs_ringtone(resultSet.getString(resultSet.getColumnIndexForName("is_ringtone")));

                musicBeans.add(musicBean);
            }
            HiLog.info(LABEL_LOG, "musicBeans size: " + musicBeans.size());
            LogUtil.info(TAG_LOG, "musicBeans size: " + musicBeans.size());

        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }

//        resultSet.close();
        SampleItemProvider sampleItemProvider = new SampleItemProvider(musicBeans, this);
        LogUtil.info(TAG_LOG, "listContainer size: " + musicBeans.size());
        listContainer.setItemProvider(sampleItemProvider);
        sampleItemProvider.update(musicBeans);
    }

    public void initView() {
        titleText = (Text) findComponentById(ResourceTable.Id_title_text);
        searchBar = (TextField) findComponentById(ResourceTable.Id_title_search);
        backButton = (Image) findComponentById(ResourceTable.Id_back_button);
        searchButton = (Image) findComponentById(ResourceTable.Id_search_button);
        recordButton = (Image) findComponentById(ResourceTable.Id_microphone_button);
        menuButton = (Image) findComponentById(ResourceTable.Id_menu_button);

        searchButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                titleText.setVisibility(Component.HIDE);
                searchBar.setVisibility(Component.VISIBLE);
                backButton.setVisibility(Component.VISIBLE);
            }
        });

        backButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                titleText.setVisibility(Component.VISIBLE);
                searchBar.setVisibility(Component.HIDE);
                backButton.setVisibility(Component.HIDE);
            }
        });

        menuButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                CommonDialog commonDialog = new CommonDialog(getContext());
                Component cpt = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_menu_item_dialog, null, false);
                commonDialog.setContentCustomComponent(cpt);
                Text about = (Text) cpt.findComponentById(ResourceTable.Id_dialog_about);
                Text showAllAudio = (Text) cpt.findComponentById(ResourceTable.Id_dialog_show_all);

                about.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        commonDialog.destroy();
                        CommonDialog dialog = new CommonDialog(getContext());
                        Component aboutComponent = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_about_dialog_layout, null, false);
                        dialog.setContentCustomComponent(aboutComponent);

                        Text dialogTitle = (Text) aboutComponent.findComponentById(ResourceTable.Id_about_dialog_title);
                        Text dialogContent = (Text) aboutComponent.findComponentById(ResourceTable.Id_about_dialog_content);
                        Text dialogOKButton = (Text) aboutComponent.findComponentById(ResourceTable.Id_dialog_ok_button);

                        dialogTitle.setText(ResourceTable.String_about_title);
                        dialogContent.setText(ResourceTable.String_about_text);
                        dialogOKButton.setClickedListener(new Component.ClickedListener() {
                            @Override
                            public void onClick(Component component) {
                                dialog.destroy();
                            }
                        });
                        dialog.setSize(900, MATCH_CONTENT);
                        dialog.show();
                    }
                });

                showAllAudio.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {

                    }
                });
                commonDialog.setSize(900, MATCH_CONTENT);
                commonDialog.setSwipeToDismiss(true);
                commonDialog.show();
            }
        });

        searchBar.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                refreshListView(searchBar.getText());
            }
        });

        recordButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                onRecord();
            }
        });
    }

    private void refreshListView(String text) {
        DataAbilityHelper dataAbilityHelper = DataAbilityHelper.creator(getContext());
        DataAbilityPredicates dataAbilityPredicates = new DataAbilityPredicates();
        // 设置查询过滤条件
        dataAbilityPredicates.contains(AVStorage.Video.Media.TITLE, text);
        List<MusicBean> musicBeans = new ArrayList<>();
        // columns为null，查询记录所有字段，当前例子表示查询id字段
        try {
            ResultSet result = dataAbilityHelper.query(AVStorage.Video.Media.INTERNAL_DATA_ABILITY_URI,
                    null, dataAbilityPredicates);
            while (result != null && result.goToNextRow()) {
                MusicBean mb = new MusicBean();
                mb.setId(result.getInt(result.getColumnIndexForName(AVStorage.AVBaseColumns.ID)));
                mb.setData(result.getString(result.getColumnIndexForName(AVStorage.AVBaseColumns.DATA)));
                mb.setAlbum(result.getString(result.getColumnIndexForName("album")));
                mb.setArtist(result.getString(result.getColumnIndexForName("artist")));
                mb.setDuration(result.getString(result.getColumnIndexForName(AVStorage.AVBaseColumns.DURATION)));
                mb.setTitle(result.getString(result.getColumnIndexForName(AVStorage.AVBaseColumns.TITLE)));
                mb.setIs_alarm(result.getString(result.getColumnIndexForName("is_alarm")));
                mb.setIs_music(result.getString(result.getColumnIndexForName("is_music")));
                mb.setIs_notification(result.getString(result.getColumnIndexForName("is_notification")));
                mb.setIs_ringtone(result.getString(result.getColumnIndexForName("is_ringtone")));
                musicBeans.add(mb);
            }
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
        SampleItemProvider sampleItemProvider = new SampleItemProvider(musicBeans, this);
        LogUtil.info(TAG_LOG, "listContainer size: " + musicBeans.size());
        listContainer.setItemProvider(sampleItemProvider);
        sampleItemProvider.update(musicBeans);
    }

    class SettingHolder {
        Text title;
        Text album;
        Text artist;
        DirectionalLayout layout;
        Image icon, menu;

        SettingHolder(Component component) {
            title = (Text) component.findComponentById(ResourceTable.Id_row_title);
            album = (Text) component.findComponentById(ResourceTable.Id_row_album);
            artist = (Text) component.findComponentById(ResourceTable.Id_row_artist);
            icon = (Image) component.findComponentById(ResourceTable.Id_row_icon);
            menu = (Image) component.findComponentById(ResourceTable.Id_row_options_button);
            layout = (DirectionalLayout) component.findComponentById(ResourceTable.Id_item_layout);
        }
    }

    class SampleItemProvider extends BaseItemProvider {
        private List<MusicBean> list;
        private AbilitySlice slice;

        SampleItemProvider(List<MusicBean> list, AbilitySlice slice) {
            this.list = list;
            this.slice = slice;
        }

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }

        @Override
        public MusicBean getItem(int position) {
            if (list != null && position >= 0 && position < list.size()) {
                return list.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        /**
         * update list data
         *
         * @param data contactDevicesData list
         */
        public void update(List<MusicBean> data) {
            list = data;
            notifyDataChanged();
        }

        @Override
        public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
            Component component;
            SettingHolder holder;
            MusicBean musicBean = list.get(position);
            if (convertComponent == null) {
                component = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_media_select_row, null, false);
                holder = new SettingHolder(component);
                component.setTag(holder);
            } else {
                component = convertComponent;
                holder = (SettingHolder) component.getTag();
            }
            holder.title.setText(musicBean.getTitle());
            holder.album.setText(musicBean.getAlbum());
            holder.artist.setText(musicBean.getArtist());

            if (musicBean.getIs_alarm().equals("1")) {
                holder.icon.setPixelMap((ResourceTable.Media_type_alarm));
                holder.layout.setBackground(ElementScatter.getInstance(component.getContext()).parse(ResourceTable.Graphic_item_click_alarm));
                holder.menu.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        showNormalDialog(component, TYPE_ALARM, musicBean);
                    }
                });
            } else if (musicBean.getIs_ringtone().equals("1")) {
                holder.menu.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        showNormalDialog(component, TYPE_RINGTONE, musicBean);
                    }
                });
                holder.icon.setPixelMap((ResourceTable.Media_type_ringtone));
                holder.layout.setBackground(ElementScatter.getInstance(getContext()).parse(ResourceTable.Graphic_item_click_ringtone));
            } else if (musicBean.getIs_music().equals("1")) {
                holder.menu.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        showNormalDialog(component, TYPE_MUSIC, musicBean);
                    }
                });
                holder.icon.setPixelMap(ResourceTable.Media_type_music);
                holder.layout.setBackground(ElementScatter.getInstance(getContext()).parse(ResourceTable.Graphic_item_click_music));
            } else if (musicBean.getIs_notification().equals("1")) {
                holder.menu.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        showNormalDialog(component, TYPE_NOTIFICATION, musicBean);
                    }
                });
                holder.icon.setPixelMap(ResourceTable.Media_type_notification);
                holder.layout.setBackground(ElementScatter.getInstance(getContext()).parse(ResourceTable.Graphic_item_click_notification));
            } else {
                holder.menu.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        showNormalDialog(component, TYPE_UNSUPPORTED, musicBean);
                    }
                });
                holder.icon.setPixelMap(ResourceTable.Media_type_ringtone);
                holder.layout.setBackground(ElementScatter.getInstance(component.getContext()).parse(ResourceTable.Graphic_item_click_unsupport));
            }
            LogUtil.info(TAG_LOG, "listContainer getId: " + list.get(position).getId());
            LogUtil.info(TAG_LOG, "listContainer getData: " + list.get(position).getData());
            LogUtil.info(TAG_LOG, "listContainer title: " + list.get(position).getTitle());
            LogUtil.info(TAG_LOG, "listContainer getIs_alarm: " + list.get(position).getIs_alarm());
            LogUtil.info(TAG_LOG, "listContainer is_ringtone: " + list.get(position).getIs_ringtone());
            LogUtil.info(TAG_LOG, "listContainer getIs_music: " + list.get(position).getIs_music());
            LogUtil.info(TAG_LOG, "listContainer getIs_notification: " + list.get(position).getIs_notification());
            return component;
        }

    }

    public void showNormalDialog(Component component, String type, MusicBean musicBean) {
        LogUtil.info(TAG_LOG, "showNormalDialog getId: " + musicBean.getId());
        CommonDialog commonDialog = new CommonDialog(component.getContext());
        Component cpt = LayoutScatter.getInstance(component.getContext())
                .parse(ResourceTable.Layout_edit_dialog_layout, null, false);
        commonDialog.setContentCustomComponent(cpt);

        Text title = (Text) cpt.findComponentById(ResourceTable.Id_dialog_title);
        Text edit = (Text) cpt.findComponentById(ResourceTable.Id_dialog_edit);
        Text delete = (Text) cpt.findComponentById(ResourceTable.Id_dialog_delete);
        Text setNotification = (Text) cpt.findComponentById(ResourceTable.Id_dialog_set_notification);
        Text setRingtone = (Text) cpt.findComponentById(ResourceTable.Id_dialog_set_ringtone);
        Text setContact = (Text) cpt.findComponentById(ResourceTable.Id_dialog_set_contact);

        title.setText(musicBean.getTitle());
        title.setVisibility(Component.VISIBLE);
        delete.setVisibility(Component.VISIBLE);
        edit.setVisibility(Component.VISIBLE);

        if (type.equals(TYPE_RINGTONE)) {
            setRingtone.setVisibility(Component.VISIBLE);
            setContact.setVisibility(Component.VISIBLE);
            setNotification.setVisibility(Component.HIDE);

        } else if (type.equals(TYPE_NOTIFICATION)) {
            setNotification.setVisibility(Component.VISIBLE);
            setRingtone.setVisibility(Component.HIDE);
            setContact.setVisibility(Component.HIDE);

        } else if (type.equals(TYPE_MUSIC)) {
            setRingtone.setVisibility(Component.HIDE);
            setContact.setVisibility(Component.HIDE);
            setNotification.setVisibility(Component.HIDE);

        } else {
            setRingtone.setVisibility(Component.HIDE);
            setContact.setVisibility(Component.HIDE);
            setNotification.setVisibility(Component.HIDE);
        }
        commonDialog.setSize(900, MATCH_CONTENT);
        commonDialog.setSwipeToDismiss(true);
        commonDialog.show();

        edit.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                startRingdroidEditor(musicBean);
                commonDialog.destroy();

            }
        });

        delete.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                confirmDelete(musicBean);
                commonDialog.destroy();
            }
        });

        setContact.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {

            }
        });

        setNotification.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {

            }
        });

        setRingtone.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {

            }
        });

    }

    private void startRingdroidEditor(MusicBean musicBean) {
        String filename = musicBean.getData();
        LogUtil.error("Ringdroid", "Uri: " + musicBean.getData());
        try {
            Intent intent = new Intent();
//            Operation operation = new Intent.OperationBuilder()
//                    .withDeviceId("")
//                    .withBundleName("com.ohos.ringdroid.core")
//                    .withAbilityName("com.ohos.ringdroid.core.MusicPlayerAbility")
//                    .withUri(Uri.parse(filename))
//                    .build();
//            intent.setOperation(operation);
            intent.setParam("was_get_content_intent", true);
            intent.setUri(Uri.parse(filename));
            present(new MusicPlayerAbilitySlice(), intent);
            LogUtil.error("Ringdroid", "Uri: " + Uri.parse(filename));
//            startAbility(intent);
        } catch (Exception e) {
            LogUtil.error("Ringdroid", "Couldn't start editor");
            LogUtil.error("Ringdroid", "Couldn't start editor: " + e);
        }
    }

    private void onRecord() {
        try {
            Intent intent = new Intent();
            intent.setParam("filename", "onRecord");
            intent.setParam("was_get_content_intent", true);
            present(new AudioRecorderSlice(), intent);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.error("Ringdroid", "Couldn't start editor");

        }
    }

    private void confirmDelete(MusicBean musicBean) {
        CommonDialog commonDialog = new CommonDialog(this);
        Component component = LayoutScatter.getInstance(getContext())
                .parse(ResourceTable.Layout_dialog_custom_layout, null, false);
        commonDialog.setContentCustomComponent(component);

        Text title = (Text) component.findComponentById(ResourceTable.Id_dialog_title);
        Button cancelButton = (Button) component.findComponentById(ResourceTable.Id_dialog_cancel);
        Button deleteButton = (Button) component.findComponentById(ResourceTable.Id_dialog_delete);

        title.setText(musicBean.getTitle());

        if (musicBean.getIs_ringtone().equals("1")) {
            title.setText("Delete Ringtone");
        } else if (musicBean.getIs_notification().equals("1")) {
            title.setText("Delete Notification");
        } else if (musicBean.getIs_alarm().equals("1")) {
            title.setText("Delete Alarm");
        } else if (musicBean.getIs_music().equals("1")) {
            title.setText("Delete Music");
        }

        cancelButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                commonDialog.destroy();
            }
        });

        deleteButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {

                // 删除ID对应文件。
                try {
                    resultSet = helper.query(AVStorage.Audio.Media.EXTERNAL_DATA_ABILITY_URI, null, null);
                    while (resultSet != null && resultSet.goToNextRow()) {
                        DataAbilityPredicates predicates = new DataAbilityPredicates();
                        predicates.equalTo(AVStorage.Audio.Media.ID, musicBean.getId());
                        int id = resultSet.getInt(resultSet.getColumnIndexForName(AVStorage.Images.Media.ID));
                        Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
                        helper.delete(uri, predicates);
                        new ToastDialog(getContext()).setText("delete success!").show();
                        commonDialog.destroy();
                    }
                } catch (DataAbilityRemoteException | SecurityException e) {
                    e.printStackTrace();
                    new ToastDialog(getContext()).setText("can not delete this file.").show();
                }


            }
        });
        commonDialog.show();
        commonDialog.setSwipeToDismiss(true);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
    }
}
